<?php defined('SYSPATH') or die('No direct access allowed.');
class lib_exception extends Exception{
    
    private $error_message = 'sorry,you meet an unknown error';
    private $error_code = 500;
    private $error_file = '';
    private $error_line = 0;
    private $error_url = '';
    
    private $_404_controller = '404';
    
    public function __construct($message = null,$code = null,$file = null,$line = null){
        if (is_string($message))
        	$this->error_message = $message;
        if (is_int($code))
        	$this->error_code = $code;
        if (is_string($file))
        	$this->error_file = $file;
        else
        	$this->error_file = basename($this->getFile());
        if (is_int($line))
        	$this->error_line = $line;
        else
        	$this->error_line = $this->getLine();
        //var_dump(lib_url::base(),lib_url::uri(),lib_url::query());
        $this->error_url = str_replace('//','/',(string)lib_url::base().lib_url::get_uri().lib_url::get_query());
        parent::__construct($this->error_message,$this->error_code);
    }
    
    public static function instance($message = null,$code = null){
        return new self($message,$code);
    }
    
    public function getArray($toJson = false){
        $error_array = array(
            'message'=>$this->getMessage(),
            'code'=>$this->getCode()
        );
        if ($toJson) return json_encode($error_array);
        return $error_array;
    }
    
    public function log($errorinf = 'error',$userId = 0){
        if (0 == $userId){
	        $user = Session::instance()->get('user');
	        if (is_object($user) && isset($user->id)){
	            $userId = $user->id;
	        }else{
	            $userId = 1;
	        }
        }
        $content = 'message=>'.$this->error_message
        .',code=>'.$this->error_code
        .',line=>'.$this->error_line;
        logunit::errorlog(intval($userId),(string)$errorinf,$content);
        return $this;
    }
    
    public function __404(){
        //Kohana_Request::current()->redirect('404');
        //header('HTTP/1.0 404 Not Found');
        header('HTTP/1.1 503 Service Temporarily Unavailable');
        header('content-type:text/html;charset=utf-8');
        if (class_exists('controller_'.$this->_404_controller)){
        	$view = Request::factory($this->_404_controller)->post(array(
	            'url'=>$this->error_url,
	        	'message'=>$this->error_message,
	            'code'=>$this->error_code,
	            'file'=>$this->error_file,
	            'line'=>$this->error_line,
	            'trace'=>$this->getTrace(),
	            'traceAsString'=>$this->getTraceAsString()
	        ))->execute();
	        echo $view;
        }else{
        	echo $this->error_message;
        }
        
        ob_flush();
        exit;
    }
    
    public function __call($name,$arguments){
        $this->__404();
    }
}